from collections import OrderedDict
from apps.goods.models import GoodsCategory
from apps.goods.models import GoodsChannel

"""
分类数据
"""


def get_categories():
    """提供首页频道分类数据"""
    # 1查询goods_channel表获取所有数据
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')

    # 2定义一个字典，组合返回的数据格式
    # OrderedDict会根据key自动排序
    categories = OrderedDict()

    # 遍历channels
    for channel in channels:
        group_id = channel.group_id
        # 2.1 把组的id作为key添加到字典
        # 判断group_id对应的数据 是否已经在字典存在
        if group_id not in categories:
            categories[group_id] = {"channels": [], "sub_cats": []}

        # 2.2一级分类数据
        # 获取当前channel的对应的一级分类
        category1 = channel.category
        # 把一级分类数据添加
        categories[group_id]["channels"].append({
            "id": category1.id,
            "name": category1.name,
            "url": channel.url
        })
        # 2.3 二级和三级分类数据
        category2s = category1.subs.all()
        for cat2 in category2s:
            # 获取当前cat2下面的三级分类数据
            category3s = cat2.subs.all()
            sub_cats3 = []  # 字典 装三级分类数据
            for cat3 in category3s:
                # 遍历三级分类数据 添加到字典sub_cats3
                sub_cats3.append({"id": cat3.id, "name": cat3.name})

            categories[group_id]["sub_cats"].append({
                "id": cat2.id,
                "name": cat2.name,
                "sub_cats": sub_cats3
            })

    return categories


"""
面包屑
"""


def get_breadcrumb(category):
    '''接收最低级别的类别, 获取各个类别的名称, 返回'''

    dict = {
        'cat1': '',
        'cat2': '',
        'cat3': '',
    }

    if category.parent is None:
        dict['cat1'] = category.name
    elif category.parent.parent is None:
        dict['cat2'] = category.name
        dict['cat1'] = category.parent.name
    else:
        dict['cat3'] = category.name
        dict['cat2'] = category.parent.name
        dict['cat1'] = category.parent.parent.name

    return dict


"""
规格选项
"""


def get_goods_specs(sku):
    # 构建当前商品的规格键
    sku_specs = sku.specs.order_by('spec_id')
    sku_key = []
    for spec in sku_specs:
        sku_key.append(spec.option.id)

    # 获取当前商品的所有SKU
    skus = sku.spu.sku_set.all()
    # 构建不同规格参数（选项）的sku字典
    spec_sku_map = {}
    for s in skus:
        # 获取sku的规格参数
        s_specs = s.specs.order_by('spec_id')
        # 用于形成规格参数-sku字典的键
        key = []
        for spec in s_specs:
            key.append(spec.option.id)
        # 向规格参数-sku字典添加记录
        spec_sku_map[tuple(key)] = s.id

    # 以下代码为：在每个选项上绑定对应的sku_id值
    # 获取当前商品的规格信息
    goods_specs = sku.spu.specs.order_by('id')
    # 若当前sku的规格信息不完整，则不再继续
    if len(sku_key) < len(goods_specs):
        return
    for index, spec in enumerate(goods_specs):
        # 复制当前sku的规格键
        key = sku_key[:]
        # 该规格的选项
        spec_options = spec.options.all()
        for option in spec_options:
            # 在规格参数sku字典中查找符合当前规格的sku
            key[index] = option.id
            option.sku_id = spec_sku_map.get(tuple(key))
        spec.spec_options = spec_options

    return goods_specs
